﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using Nox.Amuse.MVVM;

namespace Nox.Amuse
{
    public static class ObservableObjectExtensionMethods
    {
        /// <summary>
        /// Searches for the Window that is acting as the View for a given ViewModel
        /// </summary>
        /// <param name="viewModel">The viewModel that is the data context object being used by a window</param>
        /// <returns>The window containing the ViewModel, if it is not found, the MainWindow is returned instead</returns>
        public static Window GetViewModelWindow(this ObservableObject viewModel)
        {
            Window target = SearchWindowForContext(viewModel, Application.Current.MainWindow);
            if (target == null)
                return Application.Current.MainWindow;
            return target;
        }

        private static Window SearchWindowForContext(ObservableObject oo, Window window)
        {
            foreach (Window child in window.OwnedWindows)
            {
                if (child.DataContext == oo)
                    return child;
                if (child.OwnedWindows.Count > 0)
                {
                    var result = SearchWindowForContext(oo, child);
                    if (result != null)
                        return result;
                }
            }
            return null;
        }
    }
}
